/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   01.03.2010
 * @version SVN: $Id: ProductHome.java 119 2010-05-09 20:27:45Z christian-kerl@web.de $
 */

package org.cakis.server.action.impl;

import org.cakis.server.model.Product;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.framework.EntityHome;

@Name("productHome")
public class ProductHome extends EntityHome<Product>
{
    private static final long serialVersionUID = 1L;

    @RequestParameter
    private Long productId;

    @In(required=false, scope=ScopeType.CONVERSATION)
    private Product productSearchResult;

    @Override
    public Object getId()
    {
        if (productId == null)
        {
            return super.getId();
        }
        else
        {
            return productId;
        }
    }

    @Override @Begin(join=true)
    public void create() {
        super.create();
    }

    @Override
    protected Product createInstance() {
        Product result;

        if(productSearchResult != null) {
            result = productSearchResult;

            // reattach the unit object, it is detached for some strange reason
            result.getStandardQuantity().setUnit(reattach(result.getStandardQuantity().getUnit()));
        } else {
            result = super.createInstance();
        }

        return result;
    }

    private <T> T reattach(T object) {
        return getEntityManager().merge(object);
    }
}
